package edu.ncu.controller;

import edu.ncu.dao.CommentDao;
import edu.ncu.entity.Comment;
import edu.ncu.entity.Photo;
import edu.ncu.entity.Publish;
import edu.ncu.entity.User;
import edu.ncu.service.PhotoService;
import edu.ncu.service.PublishService;
import edu.ncu.service.UserService;
import edu.ncu.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j(topic = "c.PublishController")
public class PublishController {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private PublishService publishService ;
    @Autowired
    private UserService userService ;
    @Autowired
    private PhotoService photoService ;

    @Autowired
    private CommentDao commentDao ;
    // 图片上传成功之后，保存图片的路径，并将路径保存在数据库中
    private String path ;

    /**
     * 跳转至个人中心
     * 个人中心里面包括动态列表
     * @return
     */
    @GetMapping("/personal/{userId}/main")
    public String personal(HttpServletRequest request,@PathVariable int userId, Model model) {
        HttpSession session = request.getSession() ;
        User user = (User)session.getAttribute("user") ;
        // int id = user.getUserId() ;
        // User user = userService.findByUserId(userId) ;

        // 传递用户动态
        List<Publish> publishes = publishService.getPublishes(userId);
        model.addAttribute("publishes",publishes) ;

        // 传递照片
        List<Photo> photos =  photoService.findByUserId(userId) ;
        model.addAttribute("photos",photos) ;

        return "person_main" ;
    }

    /**
     * 好友列表页面
     * 根据用户id查询好友列表
     * @return
     */
    @GetMapping("/friends")
    public String getFriends(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("user") ;
        int id = user.getUserId() ;

        return "friends" ;
    }

    /**
     * 个人相册页面
     * @return
     */
    @GetMapping("/photos")
    public String getPhotos() {
        return "photos" ;
    }

    // （已测试）
    @GetMapping("/publish")
    public String publish() {
        return "publish_add" ;
    }

    // 查看某个动态的详情（已测试）
    @GetMapping("/publish/{pId}/detail")
    public String publish_details(@PathVariable int pId, Model model) {
        Publish publish = publishService.getPublishById(pId);
        model.addAttribute("publish",publish) ;
        return "publish_detail" ;
    }



    // 删除某个动态(已测试)
    @GetMapping("/publish/{pId}/delete")
    public String publish_delete(@PathVariable int pId) {
        publishService.deletePublish(pId) ;
        return "person_main" ;
    }



    /**（已测试）
     * 发布动态页面
     * 标题
     * 正文
     * 图片文件
     * 发布成功跳转至动态详情
     * （发布人，发布时间，评论数，点赞数，所有评论）
     *
     * @return
     */
    @PostMapping("/publish_add")
    public String publishAdd(@RequestParam("publish_img") MultipartFile[] file, HttpServletRequest request, String publish_title, String publish_context, Model model) throws IOException {
        // publishService.addPublish(p) ;
        Publish publish = new Publish() ;
        publish.setPTitle(publish_title);
        publish.setPContent(publish_context);
        Date date = new Date() ; // 创建时间
        publish.setPTime(date); // 设置动态创建时间
        User user = (User) request.getSession().getAttribute("user") ;
        // 测试数据
        // User user = userService.findByUserId(1) ;
        publish.setUser(user); // 设置动态创建者
        DateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss") ;

        List<String> images = null ;

        // 开始执行文件上传操作
        if (file.length > 3 ) {
            model.addAttribute("error","最多只能上传三张图片哦！") ;
        } else {
            if (file.length > 0) {
                images = new ArrayList<>() ;
            }
            for (int i = 0; i < file.length; i++) {
                //判断文件是否为空
                if (!file[i].isEmpty()) {
                    //获得原文件名
                    String fileName = file[i].getOriginalFilename();
                    String path = request.getSession().getServletContext().getRealPath("/upload/");
                    String newFileName = sdf.format(date)+fileName.substring(fileName.lastIndexOf('.')) ;
                    String name = path + newFileName ;
                    System.out.println(name);
                    FileOutputStream out = new FileOutputStream(name) ;
                    out.write(file[i].getBytes());
                    out.flush();
                    out.close();

                    String contextPath = "http://localhost:8089/makefriend/upload/"+newFileName ;
                    System.out.println(contextPath);
                    images.add(contextPath) ;
                } else {
                    log.error("文件上传异常");
                }
            }
        }

        String img1 = null,img2 = null,img3 = null ;
        int i = 0 ;
        for (String image : images) {
            if (i == 0) {
                img1 = image ;
            } else if (i == 1) {
                img2 = image ;
            } else if (i == 2) {
                img3 = image ;
            }
            ++ i ;
        }
        publish.setImg1(img1);publish.setImg2(img2);publish.setImg3(img3);
        publish.setPUId(user.getUserId());
        publish.setLikeNum(0); // 初始化点赞数
        publish.setCommentNum(0); // 初始化评论数

        publishService.addPublish(publish) ;
        publish.setImages(images);
        model.addAttribute("publish",publish) ;
        System.out.println(images);
        return "publish_detail" ;
    }

    /**
     * 点赞
     * publish:id:great  记录的是指定动态的点赞个数
     * publish:id:great:user:id 记录的是指定动态的点赞用户是谁
     * @param publishId
     * @param userId
     * @return
     */
//    @GetMapping("/great")
//    public String great(int publishId,int userId) {
//        String key = "publish"+":" +publishId + ":"
//                +"great" ;
//        Integer great = (Integer) redisUtil.get(key) ;
//        if (great == null) {
//            redisUtil.set(key,1) ;
//        } else {
//            redisUtil.set(key,great+1) ; // 点赞数+1
//        }
//        String key_user = key + ":" + "user" +":" + userId ;
//        redisUtil.set(key_user,1) ; // 保存指定用户的点赞树
//        return "/publish" ;
//    }
}






